const path = require('path')
const os = require('os')
const fs = require('fs-extra')
const readline = require('readline')
const program = require('commander')
const chalk = require('chalk')
const { execSync } = require('child_process')

const { version, author } = require('../../package.json')

function hasYarn() {
  try {
    execSync('yarn --version', { stdio: 'ignore' })
    return true
  } catch (e) {
    return false
  }
}

function enhanceErrorMessages(methodName, log) {
  program.Command.prototype[methodName] = function (...args) {
    if (methodName === 'unknownOption' && this._allowUnknownOption) {
      return
    }
    this.outputHelp()
    console.log(`  ` + chalk.red(log(...args)))
    console.log()
    process.exit(1)
  }
}

function clearScreen() {
	if (process.stdout.isTTY) {
		console.log('\n'.repeat(process.stdout.rows))
		readline.cursorTo(process.stdout, 0, 0)
		readline.clearScreenDown(process.stdout)
	}
}

// 本地存储预设配置信息路径
const rcPath = path.resolve(os.homedir(), '.genrc')

module.exports = {
  version,
  author,
  rcPath,
  hasYarn,
  isExistRcPath: fs.existsSync(rcPath),
  enhanceErrorMessages,
  clearScreen
}